package com.Pan.service.impl;

import cn.hutool.json.JSONUtil;
import com.Pan.mapper.RetryMapper;
import com.Pan.mapper.StandardRetryMapper;
import com.Pan.mapper.TongYiRetryMapper;
import com.Pan.pojo.Retry;
import com.Pan.pojo.StandardRetry;
import com.Pan.pojo.TongYiRetry;
import com.Pan.service.RetryService;
import com.Pan.util.HttpConnectionUtils;
import com.Pan.util.ResponseData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 重跑
 *
 * @author jialipan
 * @date 2021-05-24 09:44:19
 */

@Service
@Slf4j
public class RetryServiceImpl implements RetryService {

    @Autowired
    private RetryMapper retryMapper;

    @Autowired
    private StandardRetryMapper standardRetryMapper;

    @Autowired
    private TongYiRetryMapper tongYiRetryMapper;

    private Integer CODE = 200;

    // 腾讯云环境url提交：
    private final static String TX = "http://mobileout.langjtech.com/business/api/";

    // 标准环境url提交：
    private final static String BZ = "https://mobile.lenztechretail.com/business/api/";

    private final static String TY = "";

    // UAT环境url提交
    private final static String UAT = "https://perfeitti-uat.langjtech.com/business/api/";

    /**
     * 标准环境图像识别接口  新老流程自动切换
     * 一秒？条数据
     * 标准环境：String url = new String("http://39.104.68.237:10001/api/identification/v1/sendMessage/retryHistoryData");
     * insert into `t_retry` (`id`, `response_id`) values('1','4e9880e32874a74b71fd0538a089caf');
     *
     * @return
     * @throws JSONException
     * @throws InterruptedException
     * @throws IOException
     */
    @Override
    public ResponseData getImageStandardRetry(long time, Integer num, Integer overstock) throws JSONException {
        // 选择重跑环境
        String StandUrl = "https://txargus.langjtech.com/imgs_prod/api/identification/v1/sendMessage/retryHistoryData";
        try {
            // 参数一是当前页，参数二是每页个数
            Page<Retry> userPage = new Page<>(1, num);
            IPage<Retry> retryIPage = retryMapper.selectPage(userPage, null);
            // 宝洁临时项目监控页面
            String url = HttpConnectionUtils.get("http://39.104.129.72:5000/async-data");
            JSONArray backlogs = JSONObject.parseObject(url).getJSONArray("backlog");
                /*if (CollectionUtils.isNotEmpty(backlogs)) {
                    JSONArray backlog = (JSONArray) JSONObject.parseObject(url).getJSONArray("backlog").get(1);
                    log.info("当前图片积压数量为:{}", backlog.get(1));
                    if ((Integer) backlog.get(1) > overstock) {
                        log.info("进程结束!, 当前图片积压数量为:{}", backlog.get(1));
                        return new ResponseData().msg("success").data("成功！");
                    }
                }*/
            if (retryIPage.getRecords().size() == 0) {
                return new ResponseData().msg("success").data("成功！");
            }
            List<String> responseIdList = retryIPage.getRecords().stream().map(Retry::getResponseId).collect(Collectors.toList());
            String response = JSONUtil.toJsonStr(responseIdList);
            log.info("重跑rid为：{}", responseIdList);
            String str = HttpConnectionUtils.post(StandUrl, response);
            log.info("{},重跑成功！", response);
            List<Integer> id = retryIPage.getRecords().stream().map(Retry::getId).collect(Collectors.toList());
            LambdaQueryWrapper<Retry> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Retry::getId, id);
            retryMapper.delete(lambdaQueryWrapper);
            Thread.sleep(time);
        } catch (Exception e) {
            log.error("post请求超时！即将重试！异常为:{}", e);
        }
        getImageStandardRetry(time, num, overstock);
        return null;
    }

    /**
     * 旺旺腾讯云图像识别接口  新旧流程自动切换
     * insert into `t_retry` (`response_id`) values('4e9880e32874a74b71fd0538a089caf');
     *
     * @throws JSONException
     * @throws InterruptedException
     * @throws IOException
     */
    @Override
    public ResponseData getIdentificationStandardRetry(long time, Integer num) throws JSONException {
        // 选择重跑环境
//        String TencentUrl = "https://txargus.langjtech.com/imgs_tengxun/api/identification/v1/sendMessage/retryHistoryData";
        String TencentUrl = "https://txargus.langjtech.com/imgs_epsilon/api/identification/v1/sendMessage/retryHistoryData";

        // 参数一是当前页，参数二是每页个数
        Page<Retry> userPage = new Page<>(1, num);
        IPage<Retry> retryIPage = retryMapper.selectPage(userPage, null);
        List<String> responseIdList = retryIPage.getRecords().stream().map(Retry::getResponseId).collect(Collectors.toList());
        if (retryIPage.getRecords().size() == 0) {
            return new ResponseData().msg("success").data("成功");
        }
        String s = JSONUtil.toJsonStr(responseIdList);
        log.info("重跑rid为：s:{}", s);
        try {
            String str = HttpConnectionUtils.post(TencentUrl, s);
            log.info("s:{},重跑成功！", s);
            List<Integer> id = retryIPage.getRecords().stream().map(Retry::getId).collect(Collectors.toList());
            LambdaQueryWrapper<Retry> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Retry::getId, id);
            retryMapper.delete(lambdaQueryWrapper);
            Thread.sleep(time);
            getIdentificationStandardRetry(time, num);
        } catch (Exception e) {
            log.error("post请求异常！即将重试！异常为:{}", e);
            getIdentificationStandardRetry(time, num);
        }
        getIdentificationStandardRetry(time, num);
        return null;
    }

    /**
     * 统一腾讯云环境图像识别接口  新旧流程自动切换
     * String TongYiOldUrl = "http://txargus.langjtech.com/imgs_txty/api/identification/v1/sendMessage/retryHistoryData";
     *
     * @param time 休眠时间
     * @param num  重跑个数
     * @return
     */
    @Override
    public ResponseData getIdentificationTongYiStandardRetry(long time, Integer num) {
        // 选择重跑环境
        String tongYiOldUrl = "https://txargus.langjtech.com/imgs_txty/api/identification/v1/sendMessage/retryHistoryData";
        // 参数一是当前页，参数二是每页个数
        Page<TongYiRetry> userPage = new Page<>(1, num);
        IPage<TongYiRetry> retryIPage = tongYiRetryMapper.selectPage(userPage, null);
        List<String> responseIdList = retryIPage.getRecords().stream().map(TongYiRetry::getResponseId).collect(Collectors.toList());
        if (retryIPage.getRecords().size() == 0) {
            return new ResponseData().msg("success").data("成功");
        }
        String s = JSONUtil.toJsonStr(responseIdList);
        log.info("重跑rid为：{}", s);
        try {
            String str = HttpConnectionUtils.post(tongYiOldUrl, s);
            log.info("{},重跑成功！", s);
            List<Integer> id = retryIPage.getRecords().stream().map(TongYiRetry::getId).collect(Collectors.toList());
            LambdaQueryWrapper<TongYiRetry> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(TongYiRetry::getId, id);
            tongYiRetryMapper.delete(lambdaQueryWrapper);
            Thread.sleep(time);
            getIdentificationTongYiStandardRetry(time, num);
        } catch (Exception e) {
            log.error("post请求异常, 即将重试! 异常为:{}", e);
        }
        getIdentificationTongYiStandardRetry(time, num);
        return null;
    }

    /**
     * 费列罗手动回调
     *
     * @throws JSONException
     * @throws InterruptedException
     * @throws IOException
     */
    @Override
    public ResponseData getFerreroCallback(long time) throws JSONException {
        try {
            List<StandardRetry> standardRetries = standardRetryMapper.selectList(null);
            if (standardRetries.size() == 0) {
                return new ResponseData().msg("success").data("成功！");
            }
            for (StandardRetry standardRetry : standardRetries) {
                String responseId = standardRetry.getResponseId();
                log.info("重推rid：{}", responseId);
                String StandardUrl = new String("http://mobileout.langjtech.com/business/api/trax/ferrero/callbackManual?responseId=" + responseId);
                String str = HttpConnectionUtils.get(StandardUrl);
                if (str.equals("success")) {
                    System.out.println(responseId + "重推成功！");
                    log.info("{},重推成功！", responseId);
                    standardRetryMapper.deleteById(standardRetry.getId());
                    Thread.sleep(time);
                }
            }
        } catch (Exception e) {
            log.error("get请求超时！即将重试！异常为:{}", e);
        }
        getFerreroCallback(time);
        return null;
    }

    /**
     * 标准环境新流程重跑  优先使用图像识别接口
     * 标准环境重跑：String url = new String("https://mobile.lenztechretail.com/business/api/hello/image/allStepDirectSend" + "?responseId=" + responseId);
     * <p>
     * insert into `t_retry` (`id`, `response_id`) values('1','4e9880e32874a74b71fd0538a089caf');
     *
     * @return
     * @throws JSONException
     * @throws InterruptedException
     * @throws IOException
     */
    @Override
    public ResponseData getNewStandardRetry(long time, Boolean retry) throws JSONException {
        String StandardUrl = "";
        try {
            List<Retry> standardRetries = retryMapper.selectList(null);
            if (standardRetries.size() == 0) {
                return new ResponseData().msg("success").data("成功！");
            }
            for (Retry standardRetry : standardRetries) {
                String responseId = standardRetry.getResponseId();
                log.info("重跑rid为：{}", responseId);
                if (retry) {
                    StandardUrl = "http://alpha.langjtech.com/business/identifyAndCallback?responseId=" + responseId;
                } else {
                    StandardUrl = "http://alpha.langjtech.com/business/identify?responseId=" + responseId;
                }
                String str = HttpConnectionUtils.get(StandardUrl);
                Integer code = (Integer) JSONUtil.parseObj(str).get("code");
                if (CODE.equals(code)) {
                    log.info("{},重跑成功！", responseId);
                    retryMapper.deleteById(standardRetry.getId());
                    Thread.sleep(time);
                }
            }
        } catch (Exception e) {
            log.error("get请求超时！即将重试！异常为:{}", e);
        }
        getNewStandardRetry(time, retry);
        return null;
    }

    /**
     * 新流程 旺旺腾讯云环境重跑
     * insert into `t_standard_retry` (`id`, `response_id`) values('1','4e9880e32874a74b71fd0538a089caf');
     *
     * @throws JSONException
     * @throws InterruptedException
     * @throws IOException
     */
    @Override
    public ResponseData getTencentRetry(long time, Boolean retry) throws JSONException {
        String StandardUrl = "";
        try {
            List<StandardRetry> standardRetries = standardRetryMapper.selectList(null);
            if (standardRetries.size() == 0) {
                return new ResponseData().msg("success").data("成功！");
            }
            for (StandardRetry standardRetry : standardRetries) {
                String responseId = standardRetry.getResponseId();
                log.info("重跑rid为：{}", responseId);
                // DCS系统重跑
                if (retry) {
                    // 回调重跑
                    StandardUrl = "http://mobileout.langjtech.com/business/api/business/identifyAndCallback?responseId=" + responseId;
                } else {
                    // 不回调重跑
                    StandardUrl = "http://mobileout.langjtech.com/business/api/business/identify?responseId=" + responseId;
                }
                String str = HttpConnectionUtils.get(StandardUrl);
                Integer backlog = (Integer) JSONObject.parseObject(str).get("code");
                if (CODE.equals(backlog)) {
                    System.out.println(responseId + "重跑成功！");
                    log.info("{},重跑成功！", responseId);
                    standardRetryMapper.deleteById(standardRetry.getId());
                    Thread.sleep(time);
                }
            }
        } catch (Exception e) {
            log.error("get请求超时！即将重试！异常为:{}", e);
        }
        getTencentRetry(time, retry);
        return null;
    }

    /**
     * DCS系统重跑
     * <p>
     * insert into `t_standard_retry` (`id`, `response_id`) values('1','4e9880e32874a74b71fd0538a089caf');
     *
     * @throws JSONException
     * @throws InterruptedException
     * @throws IOException
     */
    @Override
    public ResponseData getDcsRetry(long time) throws JSONException {
        try {
            List<StandardRetry> standardRetries = standardRetryMapper.selectList(null);
            if (standardRetries.size() == 0) {
                return new ResponseData().msg("success").data("成功！");
            }
            for (StandardRetry standardRetry : standardRetries) {
                String responseId = standardRetry.getResponseId();
                log.info("重跑rid为：{}", responseId);
                // DCS系统重跑
                String StandardUrl = new String("http://gateway-gamma.langjtech.com/dcs/auxiliary/retryExecute/" + responseId);
                String str = HttpConnectionUtils.get(StandardUrl);
                Integer backlog = (Integer) JSONObject.parseObject(str).get("code");
                if (CODE.equals(backlog)) {
                    log.info("{},重跑成功！", responseId);
                    standardRetryMapper.deleteById(standardRetry.getId());
                    Thread.sleep(time);
                }
            }
        } catch (Exception e) {
            log.error("get请求超时！即将重试！异常为:{}", e);
        }
        getDcsRetry(time);
        return null;
    }

    /**
     * UAT 环境问卷处理
     *
     * @param time
     * @param num
     * @return
     */
    @Override
    public ResponseData uatIdentification(long time, long num) {

        String TencentUrl = "http://argus-test.langjtech.com/imgs_uat/api/identification/v1/sendMessage/retryHistoryData";

        // 参数一是当前页，参数二是每页个数
        Page<Retry> userPage = new Page<>(1, num);
        IPage<Retry> retryIPage = retryMapper.selectPage(userPage, null);
        List<String> responseIdList = retryIPage.getRecords().stream().map(Retry::getResponseId).collect(Collectors.toList());
        if (retryIPage.getRecords().size() == 0) {
            return new ResponseData().msg("success").data("成功");
        }
        String s = JSONUtil.toJsonStr(responseIdList);
        log.info("重跑rid为：s:{}", s);
        try {
            String str = HttpConnectionUtils.post(TencentUrl, s);
            log.info("s:{},重跑成功！", s);
            List<Integer> id = retryIPage.getRecords().stream().map(Retry::getId).collect(Collectors.toList());
            LambdaQueryWrapper<Retry> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Retry::getId, id);
            retryMapper.delete(lambdaQueryWrapper);
            Thread.sleep(time);
            uatIdentification(time, num);
        } catch (Exception e) {
            log.error("post请求异常！即将重试！异常为:{}", e);
            uatIdentification(time, num);
        }
        return null;
    }

    /**
     * Epsilon环境api重跑
     * insert into `t_standard_retry` (`response_id`) values('4e9880e32874a74b71fd0538a089caf');
     * @param time
     * @param retry
     * @return
     */
    @Override
    public ResponseData getEpsilonRetry(long time, Boolean retry) {
        String StandardUrl = "";
        try {
            List<StandardRetry> standardRetries = standardRetryMapper.selectList(null);
            if (standardRetries.size() == 0) {
                return new ResponseData().msg("success").data("成功！");
            }
            for (StandardRetry standardRetry : standardRetries) {
                String responseId = standardRetry.getResponseId();
                log.info("重跑rid为：{}", responseId);
                // DCS系统重跑
                if (retry) {
                    // 回调重跑
                    StandardUrl = "https://mobile-epsilon.langjtech.com/business/api/business/identifyAndCallback?responseId=" + responseId;
                } else {
                    // 不回调重跑
                    StandardUrl = "https://mobile-epsilon.langjtech.com/business/api/business/identify?responseId=" + responseId;
                }
                String str = HttpConnectionUtils.get(StandardUrl);
                Integer backlog = (Integer) JSONObject.parseObject(str).get("code");
                if (CODE.equals(backlog)) {
                    log.info("{},重跑成功！,是否重推:{}", responseId, retry);
                    standardRetryMapper.deleteById(standardRetry.getId());
                    Thread.sleep(time);
                }
            }
        } catch (Exception e) {
            log.error("get请求超时！即将重试！异常为:{}", e);
        }
        getEpsilonRetry(time, retry);
        return null;
    }

}
